package com.why.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import javax.sql.DataSource;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetails s;
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from tb_user where username=?")
                .authoritiesByUsernameQuery("select username,authority from tb_authority where username=?")
                .passwordEncoder(NoOpPasswordEncoder.getInstance());// 数据库存放的是明码
     //   super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.authorizeRequests()
                .antMatchers("/login","/user/loginoutOK","/user/noLogin","/mylogin.html","/user/foretPassword").permitAll()  //表示允许
                .antMatchers("/**").authenticated()  // 需要认证的
                .and().
                    //formLogin().loginPage("/mylogin.html")// 登录页面  普通场景
                formLogin().loginPage("/user/noLogin")// 需要登陆 自己提供
                .loginProcessingUrl("/myprocesslogin") // 接受用户名和密码的资源地址
                .successForwardUrl("/user/loginOK") //登录成功 跳转的资源地址 自己提供
                .failureForwardUrl("/user/loginFAIL") //登录失败 跳转的资源地址 自己提供
                .and().logout().logoutUrl("/myLoginout") //不需要自己提供
                .logoutSuccessUrl("/user/loginoutOK") // 登出之后 提供资源路径 自己提供 反馈给前端
        ;
        http.headers().cacheControl();// 不需要缓存控制
        http.csrf().disable();// 禁用跨域攻击
        http.cors(); //允许跨域访问
    }
}
